/**
 * Created by charsen on 16/5/31.
 */
main.controller('dbManagerCtrl', ["$scope", "$rootScope", "tools", "$timeout","$compile","$location","$route", function ($scope, $rootScope, tools, $timeout,$compile,$location,$route) {
    $('#slider-list').height(document.documentElement.clientHeight - 98);
    $('.dbManager-container').height(document.documentElement.clientHeight);
    $('#tableBox').height(document.documentElement.clientHeight - $("#rightBox .tableLink").height() - $("#rightBox .tool").height() - 90);
    //下拉菜单
    $('.dropdown').dropdown();

    $("#tableBox").on("scroll", function () {
        $("#tableLayout .Top").css({"top": $("#tableBox").scrollTop() + "px"});
    });

    //提示框
    $('i.popup').popup();

    $scope.lookUpMyS = function(){
        $rootScope.$broadcast("showMySheet_EV","look");
    };

    /*
     * init 数据初始化
     * */

    // 数据源
    $scope.dataSources = [];

    tools.get({
        method: 'POST',
        url: '/Ibm-Client/getLoginUserInfo.htm',
        data: {},
        succ: function (resp) {
            if (resp.success) {

                for (var i in resp.value.dataSources) {
                    $scope.dataSources.push(resp.value.dataSources[i]);
                }

               // sysOut("$scope.dataSources:", $scope.dataSources);
                if ($.isEmptyObject(resp.value.dataSources)) {
                    return;
                }
                console.log($scope.dataSources.length-1);
                $scope.changeSource($scope.dataSources.length-1);//DataSource $index
            } else {
                $timeout(function(){
                    $rootScope.$broadcast("MESSAGE_EV","数据异常，请找管理员联系。");
                    return;
                },500);
            }
        }
    });


    //删除数据源
    $scope.delSource = function(){
        $rootScope.key = Math.floor(Math.random()*1000000000);
        $rootScope.$broadcast("delSource_EV",$scope.dataSources,$rootScope.key);
    };

    //页面清空init
    $rootScope.$on("dbManage_Init_EV",function(){
    	$scope.currTable = null;
        $scope.currTable = {
            isShowAll: false,
            hasNullData: false,
            connectLinkAble: false,
            mulConnectLinkAble: false,
            limitNum: 100
        };
        $scope.table1 = null;
        $scope.currIbmTable = {};
        $scope.fyTable = {};
        $(".tableLink").find("svg").remove();
        $scope.tablesCard = [];
        $scope.panelShow=false;
        $scope.mulRelationAble = false;
        $scope.aggregateAble = false;

    });


    //数据表
    $scope.dbTables = {
        base: [],
        relation: [],
        filetable: [],
        aggregation: [],
        mulRelation: []
    };

    // 获取数据源基础数据--base
    function getIbmTables(sourceId) {
        $scope.dbTables.base = [];
        tools.get({
            url: '/Ibm-Client/getIbmTables.htm',
            method: 'POST',
            data: {
                type: 'table',
                dataSourceId: sourceId
            },
            succ: function (resp) {
                if (resp.success) {
                    /* $timeout(function () {
                     $scope.base_tables_shown = true;
                     }, 0);*/
                    $timeout(function(){
                        $scope.dbTables.base = resp.value;
//                        $scope.base_tables_shown = true;
                        if ($.isEmptyObject($scope.dbTables.base)) {
                            $timeout(function () {
                                $scope.base_tables_shown = false;
                            }, 0);
                        } else {
                            $timeout(function () {
                                $scope.base_tables_shown = true;
                            }, 0);
                        }
                    },0);

                } else {
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","数据源基础数据数据异常，请找管理员联系。");
                        return;
                    },500);
                }
            }
        });
    }

    // 获取关联关系数据--relation
    function getIbmRelationTables(sourceId) {
        $scope.dbTables.relation = [];
        tools.get({
            url: '/Ibm-Client/getIbmRelationTables.htm',
            method: 'POST',
            data: {
                type: 'table',
                dataSourceId: sourceId
            },
            succ: function (resp) {
                if (resp.success) {
                    $timeout(function () {
                        $scope.relation_tables_shown = true;
                        $scope.dbTables.relation = resp.value;
                    }, 0);

                    if ($.isEmptyObject($scope.dbTables.relation)) {
                        $timeout(function () {
                            $scope.relation_tables_shown = false;
                        }, 0);
                    } else {
                        $timeout(function () {
                            $scope.relation_tables_shown = true;
                        }, 0);
                    }
                } else {
                    //alert(resp.message);
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","数据异常，请找管理员联系。");
                        return;
                    },500);
                }
            }
        });
    }

    // 获取多表关联数据--mulRelation
    function getIbmMultiRelationTables(sourceId) {
        $scope.dbTables.mulRelation = [];
        tools.get({
            url: '/Ibm-Client/getMultiRelationTables.htm',
            method: 'POST',
            data: {
                type: 'table',
                dataSourceId: sourceId
            },
            succ: function (resp) {
                if (resp.success) {
                    /*$timeout(function () {
                     $scope.mulRelation_tables_shown = false;
                     }, 0);*/
                    $timeout(function(){
                        $scope.dbTables.mulRelation = resp.value;
                        if ($.isEmptyObject($scope.dbTables.mulRelation)) {
                            $timeout(function () {
                                $scope.mulRelation_tables_shown = false;
                            }, 0);
                        } else {
                            $timeout(function () {
                                $scope.mulRelation_tables_shown = true;
                            }, 0);
                        }
                    },0);

                } else {
//                    alert(resp.message);
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","多表关联数据数据异常，请找管理员联系。");
                        return;
                    },500);
                }
            }
        });
    }

    // 获取分类汇总数据--aggregation
    function getIbmAggregateFunctions(sourceId) {

        $scope.dbTables.aggregation = [];
        tools.get({
            url: '/Ibm-Client/getIbmAggregateFunctions.htm',
            method: 'POST',
            data: {
                type: 'table',
                dataSourceId: sourceId
            },
            succ: function (resp) {
                if (resp.success) {
                    /*$timeout(function () {
                     $scope.aggregation_tables_shown = false;
                     }, 0);*/
                    $timeout(function(){
//                        $scope.aggregation_tables_shown = false;
                        $scope.dbTables.aggregation = resp.value;
                        if ($.isEmptyObject($scope.dbTables.aggregation)) {
                            $timeout(function () {
                                $scope.aggregation_tables_shown = false;
                            }, 0);
                        } else {
                            $timeout(function () {
                                $scope.aggregation_tables_shown = true;
                            }, 0);
                        }
                    },0);

                } else {
//                    alert(resp.message);
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","分类汇总数据数据异常，请找管理员联系。");
                        return;
                    },500);
                }
            }
        });
    }

    // 获取上传数据--fileTable
    function getFileTableFunctions(sourceId) {
        $scope.dbTables.filetable = [];
        tools.get({
            url: '/Ibm-Client/getFileTables.htm',
            method: 'POST',
            data: {
                type: 'table',
                dataSourceId: sourceId
            },
            succ: function (resp) {
                if (resp.success) {

                    $timeout(function(){
                        $scope.dbTables.filetable = resp.value;
                        if ($.isEmptyObject($scope.dbTables.filetable)) {
                            $timeout(function () {
                                $scope.file_tables_shown = false;
                            }, 0);
                        } else {
                            $timeout(function () {
                                $scope.file_tables_shown = true;
                            }, 0);
                        }
                    },0);

                } else {
//                    alert(resp.message);
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","上传数据数据异常，请找管理员联系。");
                        return;
                    },500);
                }
            }
        });
    }

    $scope.currTable = {
        isShowAll: false,
        hasNullData: false,
        connectLinkAble: false,
        mulConnectLinkAble: false,
        limitNum: 100
    };
    $scope.currIbmTable = {};
    $scope.fyTable = {};
    //获取一张表
    function getTable(tbId, tableType) {

        $scope.cancelMulConLink();

        //防止关联后的界面出现-多表关联的返回ID
        $scope.mulrelationDataTbId = null;

        $scope.currIbmTable = null;

        $rootScope.$broadcast("loading_Start_EV");
        tools.get({
            method: 'POST',
            url: '/Ibm-Client/getDbTableDatas.htm',
            data: {
                tbId: tbId,
                tableType: tableType,
                beginIndex: 0,
                resultSize: $scope.numInPerPage
            },
            succ: function (resp) {

                /*$timeout(function(){
                 $rootScope.$broadcast("loading_End_EV");
                 },10);*/

                if (resp.success) {

                    $scope.totalSize = resp.value.totalPages * $scope.numInPerPage;
                    $scope.currTable = {
                        isShowAll: false,
                        hasNullData: false,
                        connectLinkAble: false,
                        limitNum: 100
                    };

                    $scope.currIbmTable = resp.value;


                    //是否为空
                    if ($.isEmptyObject($scope.currIbmTable.datas)) {
                        $scope.currTable.hasNullData = true;
                    }
                    $timeout(function () {
                        $('.dropdown').dropdown();

                        if ($("#tableLayout thead tr").width() < $("#tableLayout").width()) {

                            var tdsObj = $("#tableLayout tbody tr:first td");
                            var thsObj = $("#tableLayout thead tr th");


                            for (var i = 0; i < thsObj.length; i++) {
                               // console.log(tdsObj.eq(i).width());
                                if (tdsObj.eq(i).width() == null) {
                                    thsObj.eq(i).css({"width": ($("#tableLayout").width() / thsObj.length) + "px"});
                                } else {
                                    thsObj.eq(i).css({"width": tdsObj.eq(i).outerWidth() + "px"});
                                }

                            }
                        }
                        $rootScope.$broadcast("loading_End_EV");

                    }, 50);
                  // console.log($scope.currIbmTable);
                  //  console.log($scope.currTable);

                    $scope.pagination = {
                        current: 1
                    };
                    myThPosition();
                } else {
                    $rootScope.$broadcast("loading_End_EV");
//                    alert(resp.message);
                    $timeout(function(){

                        $rootScope.$broadcast("MESSAGE_EV","数据异常，请找管理员联系。");
                        return;
                    },500);
                }
            }
        });
    }

    $scope.currSource = null;
    // 切换数据源 && get Table
    $scope.changeSource = function (index) {
        $scope.table1=null;
        $scope.currIbmTable=null;
        var sourceId = $scope.dataSources[index].sourceId;
        $scope.tablesCard = [];
        tools.get({
            method: 'POST',
            url: '/Ibm-Client/changeDataSource.htm',
            data: {
                sourceId: sourceId
            },
            succ: function (resp) {
                if (resp.success) {

                } else {
//                    alert(resp.message);
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","数据异常，请找管理员联系。");
                        return;
                    },500);
                }
            }
        });
        if ($scope.currSource != null && sourceId == $scope.currSource.sourceId) {
           // sysOut("$scope.currSource.sourceId没有改变", $scope.currSource.sourceId);
            return;
        }
        $scope.dbTables = {
            base: [],
            relation: [],
            filetable: [],
            aggregation: [],
            mulRelation: []
        };


        $scope.currSource = $scope.dataSources[index];
       // sysOut("sourceId:", sourceId);

        getIbmTables(sourceId);
        //getIbmRelationTables(sourceId);
        getIbmMultiRelationTables(sourceId);
        getIbmAggregateFunctions(sourceId);
        getFileTableFunctions(sourceId);
    };

    $rootScope.$on("UpdateSliderTable_EV", function (e, data) {
       // console.log(data);
        UpdateSliderTable(data);
    });

    //slide的数据表的更新
    function UpdateSliderTable(dataType) {
        if (dataType == "Ibm") {
            getIbmTables($scope.currSource.sourceId);
        } else if (dataType == "mulRel") {
            getIbmMultiRelationTables($scope.currSource.sourceId);
        } else if (dataType == "Agg") {
            getIbmAggregateFunctions($scope.currSource.sourceId);
        } else if (dataType == "File") {
            getFileTableFunctions($scope.currSource.sourceId);

        } else if (dataType == "UpdateSliderTable_EV") {
            getIbmMultiRelationTables($scope.currSource.sourceId);
        } else {
            getIbmTables($scope.currSource.sourceId);
            getIbmRelationTables($scope.currSource.sourceId);
            getIbmMultiRelationTables($scope.currSource.sourceId);
            getIbmAggregateFunctions($scope.currSource.sourceId);
            getFileTableFunctions($scope.currSource.sourceId);
        }
    }

    function updateMyTable(tableType){
        if (tableType == "base") {
            getIbmTables($scope.currSource.sourceId);
        } else if (tableType == "relation") {
            getIbmRelationTables($scope.currSource.sourceId);
        } else if (tableType == "aggregation") {
            getIbmAggregateFunctions($scope.currSource.sourceId);
        } else if (tableType == "file") {
            getFileTableFunctions($scope.currSource.sourceId);
        } else if (tableType == "multi_relation") {
            getIbmMultiRelationTables($scope.currSource.sourceId);
        }else{
            getIbmTables($scope.currSource.sourceId);
            getIbmRelationTables($scope.currSource.sourceId);
            getIbmMultiRelationTables($scope.currSource.sourceId);
            getIbmAggregateFunctions($scope.currSource.sourceId);
            getFileTableFunctions($scope.currSource.sourceId);
        }
    }

    /**
     * getDbTableDatas 获取表Table
     * @param tbId 表的tbId
     * @param tableType 表的类型
     * @param tableName 表的名称
     * @param dataType 该表的所在的库
     */

    $scope.getDbTableDatas = function (tbId, tableType, tableName, dataType, event) {
        $scope.fyTable = {};
        $scope.fyTable.tbId = tbId;
        $scope.fyTable.tableType = tableType;
        $scope.fyTable.tableName = tableName;
        $scope.fyTable.dataType = "table";
        event.preventDefault();
        if (event.target.nodeName == "I") {
            return;
        }
        if($scope.aggregateAble ||$scope.mulRelationAble){
            $rootScope.$broadcast("MESSAGE_EV","请先完成保存操作！");
            return;
        }

        if (!$scope.currTable.connectLinkAble) {

            if ($scope.table1 != null && $scope.table1.tbId != null && tbId == $scope.table1.tbId) {
                //sysOut("没有切花表", $scope.table1);
                return;
            }
            $scope.table1 = {'tbId': tbId, 'tableType': tableType, 'tableName': tableName, 'dataType': dataType};

        }
        else {
//            $scope.table1={'tbId': tbId, 'tableType': tableType, 'tableName': tableName, 'dataType': dataType};
            $scope.table2 = {'tbId': tbId, 'tableType': tableType, 'tableName': tableName, 'dataType': dataType};
            $rootScope.$broadcast('Show_tableConnect_EV', [$scope.table1, $scope.table2]);//表的关联关系组件-tableConnect

            return;

        }
       // console.log("AAAAA");
        getTable(tbId, tableType);
    };

    //新建数据库
    $scope.addNewSource = function () {
        $rootScope.$broadcast('ADD_NEW_SOURCE_EV');
    };

    //连接数据源后的数据源的更新
    $rootScope.$on("addSource_Update_EV", function () {
        $scope.dataSources = [];
        tools.get({
            method: 'POST',
            url: '/Ibm-Client/getLoginUserInfo.htm',
            data: {},
            succ: function (resp) {
//                alert(00209);
                if (resp.success) {

                    for (var i in resp.value.dataSources) {
                        $scope.dataSources.push(resp.value.dataSources[i]);
                    }
                    if ($.isEmptyObject(resp.value)) {
                        return;
                    }
                    $scope.changeSource($scope.dataSources.length-1);//DataSource $index
                } else {
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","数据源的更新异常，请找管理员联系。");
                        return;
                    },500);
                    //alert(resp.message);
                }
            }
        });
    });

    // 上传数据文件
    $scope.addNewFile = function () {
        if ($scope.currSource == null) {
            $rootScope.$broadcast('MESSAGE_EV', '请先选择数据源');
            return;
        }
        $rootScope.$broadcast('Up_File_EV');
    };

    // 增加表数据
    $scope.addTable = function () {
        if ($scope.currSource) {

            $rootScope.$broadcast('ADD_TABLE_EV', $scope.currSource.sourceId, $scope.currSource.sourceName);
        } else {
            $rootScope.$broadcast('MESSAGE_EV', '请先选择数据源');
        }
    };

    //导入新表的更新
    $rootScope.$on("addNewTable_EV", function () {
        getIbmTables($scope.currSource.sourceId);
    });


    /*分页*/

    $scope.numInPerPage = 25;
    $("#changeTableRowsValue").val($scope.numInPerPage);
    //改变最多Perpage记录
    $scope.rowsChange = function () {
        if ($scope.aggregateAble || $scope.relationAble || $scope.mulRelationAble) {
            $("#changeTableRowsValue").val($scope.numInPerPage);
            return;
        }
       // console.log($("#changeTableRowsValue").val());
        var value = $("#changeTableRowsValue").val();
        var reg = new RegExp("^[0-9]*[1-9][0-9]*$");
        if (!reg.test(value)) {
            $("#changeTableRowsValue").val($scope.numInPerPage);
        } else {
            $scope.numInPerPage = value;
            getTable($scope.fyTable.tbId, $scope.fyTable.tableType);
        }
    };
    $scope.rowsKeyDown =  function(event){
        if (event.keyCode == "13") {
            $scope.rowsChange();
        }
    };
    $scope.rowsInit = function (value,event) {
        //console.log(event.target);
        var target = event.target;
        if($(target).hasClass("active")){
            //console.log("is m");
            return;
        }
        $(target).addClass("active").siblings(".active").removeClass("active");
        $scope.numInPerPage = value;
        $("#changeTableRowsValue").val($scope.numInPerPage);
        getTable($scope.fyTable.tbId, $scope.fyTable.tableType);
    };

    $scope.pageChanged = function (newPage) {
        if($scope.totalSize<=$scope.numInPerPage){
           // console.log("不足一页，不分页");
            return;
        }
        if (newPage == 0) {
            $scope.pagination = {
                current: 1
            };
            return;
        }
       // console.log("newPage:" + newPage);

        getResultsPage(newPage);

    };


    $scope.totalSize = 0;
    $scope.pagination = {
        current: 1
    };
    //分页获取数据

    function getResultsPage(pageNumber) {
       /* console.log({
            tbId: $scope.fyTable.tbId,
            tableType: $scope.fyTable.tableType,
            beginIndex: pageNumber * $scope.numInPerPage,
            resultSize: $scope.numInPerPage
        });*/
        $scope.currIbmTable.datas = [];
        if ($scope.fyTable.dataType = "table") {
            tools.get({
                url: "/Ibm-Client/getDbTableDatas.htm",
                data: {
                    tbId: $scope.fyTable.tbId,
                    tableType: $scope.fyTable.tableType,
                    beginIndex: (pageNumber - 1) * $scope.numInPerPage,
                    resultSize: $scope.numInPerPage
                },
                succ: function (resp) {
                    /*if (pageNumber == 1) {

                    }*/
                  //  console.log("分页");
                    if (resp.success) {

                       // $scope.currIbmTable = resp.value;
                        angular.forEach(resp.value.datas,function(item ){
                            $scope.currIbmTable.datas.push(item);
                        });
                        //是否为空
                        if ($.isEmptyObject($scope.currIbmTable.datas)) {
                            $scope.currTable.hasNullData = true;
                        }
                        $timeout(function () {
                            $('.dropdown').dropdown();
                        }, 1000);
                       myThPosition();
                    } else {
                        $timeout(function(){
                            $rootScope.$broadcast("MESSAGE_EV","数据异常，请找管理员联系。");
                            return;
                        },500);
                       // alert(resp.message);
                    }
                }
            });
        }

    }

//th
    var myTableMenu = [
        {
            name: '重命名',
            icon: 'table icon',
            fn: function (){
                $rootScope.$broadcast('EditorOneInput_EV', {
                    title: '重命名',
                    data: $scope.delT.tableDesc,
                    type: 'tableRename',
                    id: $scope.key
                });
            }

        },
        {
            name: '可视化',
            icon: 'pie chart icon',
            fn: function (){
                // alert("关联");
                $rootScope.$broadcast("NEW_PAGE_FROM_DATA_MANAGER",{"tbId":$scope.delT.tbId,"tableType": $scope.delT.tableType,"tableDesc":$scope.delT.tableDesc});
            }

        },
        {
            name: '删除',
            icon: 'remove icon',
            fn: function () {
                var tableMessage = '';
                var pageMessage = '';
                tools.get({
                    url:'/Ibm-Client/getMeanwhileDeleteInfosBeforeDeleteTable.htm',
                    data:{
                        tbId : $scope.delT.tbId,
                        tableType: $scope.delT.tableType,
                    },
                    succ:function(resp){
                        if(resp.success){
                            tableMessage = resp.value.tables;
                            pageMessage = resp.value.pages;
                            var msg = '';
                            if($.isEmptyObject(resp.value.pages)){
                                msg = '删除后基于该表的 '+'表: '+tableMessage+' 都将无法使用'
                            }else{
                                msg = '删除后基于该表的 '+'表: '+tableMessage+' 报表: '+pageMessage+' 都将无法使用'
                            }
                            $rootScope.$broadcast('CONFIRM_EV', {
                                title: '删除提醒',
                                content: msg,
                                btns: {
                                    no: {
                                        text: '取消',
                                        fn: function () {
                                            //$rootScope.$broadcast("cancel_delTable_EV");
                                        }
                                    },
                                    yes: {
                                        text: '删除',
                                        fn: function () {
                                            $rootScope.$broadcast("confirm_delTable_EV",$scope.key);
                                        }
                                    }
                                }
                            });
                        }else{

                        }
                    }
                });

                // $rootScope.$broadcast("removeLinkTable",$scope.linkTablesShowKey);
            }

        }
    ];
    //
    $scope.showMyTableMenu = function(index,e,type){
        $scope.delT = {};
        if(type=="base"){

            $scope.delT.tbId = $scope.dbTables.base[index].tbId;
            $scope.delT.tableType = $scope.dbTables.base[index].tableType;
            $scope.delT.tableDesc = $scope.dbTables.base[index].tableDesc;
        }else if(type=='relation'){

            $scope.delT.tbId = $scope.dbTables.relation[index].tbId;
            $scope.delT.tableType = $scope.dbTables.relation[index].tableType;
            $scope.delT.tableDesc = $scope.dbTables.relation[index].tableDesc;
        }else if(type=='mulRelation'){

            $scope.delT.tbId = $scope.dbTables.mulRelation[index].tbId;
            $scope.delT.tableType = $scope.dbTables.mulRelation[index].tableType;
            $scope.delT.tableDesc = $scope.dbTables.mulRelation[index].tableDesc;
        }else if(type=='aggregation'){

            $scope.delT.tbId = $scope.dbTables.aggregation[index].tbId;
            $scope.delT.tableType = $scope.dbTables.aggregation[index].tableType;
            $scope.delT.tableDesc = $scope.dbTables.aggregation[index].tableDesc;
        }else if(type=='filetable'){

            $scope.delT.tbId = $scope.dbTables.filetable[index].tbId;
            $scope.delT.tableType = $scope.dbTables.filetable[index].tableType;
            $scope.delT.tableDesc = $scope.dbTables.filetable[index].tableDesc;
        }else{
            return;
        }

        //$scope.delT.dataType = dataType;
        $scope.key = Math.floor(Math.random()*1000000000);
        $rootScope.$broadcast('CONTEXTMENU_EV', e.pageX, e.pageY, myTableMenu);
    };
//    $scope.delT = {};
    //删除表
    $scope.delTable = function (tbId, tableType, dataType) {
       // console.log("要删除" + tbId + " " + tableType);
        $scope.delT.tbId = tbId;
        $scope.delT.tableType = tableType;
        $scope.delT.dataType = dataType;

        $rootScope.$broadcast('CONFIRM_EV', {
            title: '删除提醒',
            content: '是否删除该表 删除后基于该表的 视图／表／数据 都将无法使用',
            btns: {
                no: {
                    text: '取消',
                    fn: function () {
                        $rootScope.$broadcast("cancel_delTable_EV");
                    }
                },
                yes: {
                    text: '删除',
                    fn: function () {
                        $rootScope.$broadcast("confirm_delTable_EV");
                    }
                }
            }
        });
    };

    $rootScope.$on('confirm_delTable_EV', function (e,key) {
        if(key==$scope.key){
            $scope.key = Math.floor(Math.random()*1000000);
            tools.get({
                method: 'POST',
                url: '/Ibm-Client/deleteTable.htm',
                data: {
                    tableType: $scope.delT.tableType,
                    tbId: $scope.delT.tbId
                },
                succ: function (resp) {
                    if (resp.success) {


                        $rootScope.$broadcast('MESSAGE_EV', '删除成功');

                        //更新表数据
                        updateMyTable("all");

                       // console.log('删除成功');
                        $scope.delT = {};
                        $scope.currIbmTable = null;
                        $scope.table1 = null;
                        $scope.table2=null;
                        $rootScope.$broadcast("dbManage_Init_EV");

                    } else {
                        $timeout(function(){
                            $rootScope.$broadcast("MESSAGE_EV","数据删除异常，请找管理员联系。");
                            return;
                        },500);
                        //alert(resp.message);
                    }
                }
            });
        }

    });

    //重命名
    $rootScope.$on("myTable_Rename_EV",function(e,value,Id){
        //console.log("id:"+Id+" key:"+$scope.key);
        if(Id==$scope.key){
            $scope.key = Math.floor(Math.random()*1000000000);
            tools.post({
                url: '/Ibm-Client/updateTable.htm',
                data: {
                    tbId : $scope.delT.tbId,
                    tableType: $scope.delT.tableType,
                    tableDesc: value
                },
                succ: function (resp) {
                    if (resp.success) {

                        updateMyTable($scope.delT.dataType);
                        $rootScope.$broadcast("MESSAGE_EV","重命名表成功");
                    } else {
                        $rootScope.$broadcast("MESSAGE_EV","重命名表失败");
                        //alert(resp.message);
                    }
                }
            });

        }
    });

    /*-------------------------------------------------------菜单条 .tool------------------------------------------------*/
    $scope.tableLayout = {
        tableLayout: true,
        thLayout: false
    };

    //移除table
    $scope.removeTable = function (index) {

        if (index == 1) {
            $scope.table1 = $scope.table2;
            $scope.table2 = null;


        } else if (index == 2) {
            $scope.table2 = null;
        }
        $scope.aggregateAble = false;
        $scope.currIbmTable = {};
        $scope.currTable = {
            isShowAll: false,
            hasNullData: false,
            connectLinkAble: false,
            mulConnectLinkAble: false,
            limitNum: 100
        };
    };
    $timeout(function () {
        $scope.tableLayout.tableLayout = true;
    }, 0);
    //表的转化
    $scope.tableListLayout = function (index) {
        if (index == 0) {
            if ($scope.tableLayout.tableLayout) {
               // sysOut("已结是自己", $scope.tableLayout.tableLayout);
                return;
            }
            $scope.tableLayout.tableLayout = true;
            $scope.tableLayout.thLayout = false;
        } else {
            if ($scope.tableLayout.thLayout) {
               // sysOut("已结是自己", $scope.tableLayout.thLayout);
                return;
            }
            $scope.tableLayout.tableLayout = false;
            $scope.tableLayout.thLayout = true;
        }
    };
//字段的重命名  -index
    $scope.setColName = {};
    $scope.thRename = function (index, value) {
        $scope.setColName.index = index;
        $scope.setColName.value = value;
        if ($scope.tableLayout.thLayout) {//列表模式
            $timeout(function () {
                $("#thLayout td .input.ui input").eq(index).focus();
            }, 100);
        } else {
            $timeout(function () {
                $("#tableLayout th .input.ui input").eq(index).focus();
            }, 100);
        }

    };

    $scope.remaneKey = false;//开关
    $scope.remaneMyTd = function (index) {
      //  console.log($scope.remaneKey);
        if ($scope.remaneKey) {
            return;
        }
      //  console.log(1);
      //  console.log($scope.setColName.value);
        $scope.setColName.index = -1;
        var name = $scope.setColName.value;
        if (name == $scope.currIbmTable.columns[index].columnDesc) {
           // sysOut("值相同", name);
            return;
        }
        $scope.currIbmTable.columns[index].columnDesc = name;
        var id = $scope.currIbmTable.columns[index].columnId;
       // console.log($scope.setColName.value);
        $scope.setColName.index = -1;
        reColName(name, id);

    };
    $scope.keyEnter = function (event, index) {
      //  console.log("1");
      //  console.log(event.keyCode);
        if (event.keyCode == "13") {
            $scope.remaneKey = true;
            var name = $scope.setColName.value;
            /*if (name == $scope.currIbmTable.columns[index].columnDesc) {
                sysOut("值相同", name);
                return;
            }*/
            $scope.currIbmTable.columns[index].columnDesc = name;
            var id = $scope.currIbmTable.columns[index].columnId;
          //  console.log($scope.setColName.value);
            $scope.setColName.index = -1;


            reColName(name, id);
        }
    };
    function reColName(name, id) {
        tools.get({
            url: '/Ibm-Client/updateColumn.htm',
            method: 'POST',
            data: {
                tableType: $scope.table1.tableType,
                tbId: $scope.table1.tbId,
                columnId: id,
                columnDesc: name
            },
            succ: function (resp) {
                if (resp.success) {
                    $rootScope.$broadcast('MESSAGE_EV', '修改成功');
                    $scope.remaneKey = false;
                } else {
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                        return;
                    },500);
                   // alert(resp.message);
                }
            }
        });
    }

//sort 字段
    $scope.sortKey = "";
    $scope.reverse = false;
    $scope.sortByKey = function (key) {
        $scope.reverse = !$scope.reverse;
        $scope.sortKey = key;
    };

//  添加字段、计算字段
    $scope.counter = function () {
        if ($scope.fyTable == null || $scope.table1 == null) {
            $rootScope.$broadcast('MESSAGE_EV', "请先选择一张表");
            return;
        }
        if($scope.aggregateAble || $scope.mulRelationAble){
            $rootScope.$broadcast('MESSAGE_EV', "请先完成保存操作");
            return;
        }
        $rootScope.$broadcast('Show_CounterView_EV', $scope.fyTable);//table1
    };
    //更新
    $rootScope.$on('update_tableCounter_EV', function (e, tbId, tableType) {
        getTable(tbId, tableType);

    });


    //显示隐藏的字段
    /* $(".hideBox").checkbox({
     onChecked: function() {
     $scope.currIbmTable.isShowAll=true;
     $scope.$apply();
     alert($scope.currIbmTable.isShowAll);

     },
     onUnchecked: function() {

     $scope.currIbmTable.isShowAll=false;
     $scope.$apply();
     alert($scope.currIbmTable.isShowAll);
     }
     });*/
    //隐藏模一字段
    /**
     *
     * @param index
     * @param id 0-不隐藏 1-隐藏
     */
    $scope.hideTableTd = function (index, id) {
        var columnId = $scope.currIbmTable.columns[index].columnId;
        var tableType = $scope.currIbmTable.columns[index].tableType;
        var tbId = $scope.currIbmTable.columns[index].tbId;
        var isShow = false;
        var txt = "";
        if (id == 0) {
            isShow = true;
            txt = "显示成功";
        } else {
            isShow = false;
            txt = "隐藏成功";
        }
        tools.get({
            url: '/Ibm-Client/updateColumn.htm',
            method: 'POST',
            data: {
                tableType: tableType,
                tbId: tbId,
                columnId: columnId,
                isShow: isShow
            },
            succ: function (resp) {
                if (resp.success) {
                    $rootScope.$broadcast('MESSAGE_EV', txt);
                    $scope.currIbmTable.columns[index].isShow = isShow;
                    myThPosition();
                } else {
                    $rootScope.$broadcast('MESSAGE_EV', 'Error：出现错误');
                    //alert(resp.message);
                }
            }
        });
    };

    //下载
    /*$scope.exportTo = function (type) {
        if ($scope.table1 == null) {
            $rootScope.$broadcast('MESSAGE_EV', "请先选择一张表");
            return;
        }
        if (type == "excel") {
            $('#tableBox').tableExport({type: 'excel', escape: 'false', fileName: $scope.table1.tableName });
        } else if (type == "doc") {
            $('#tableLayout').tableExport({type: 'doc', escape: 'false', fileName: $scope.table1.tableName });
        } else if (type == "sql") {
            $('#tableLayout').tableExport({type: 'sql', escape: 'false', tableName: $scope.table1.tableName });
        }
    };*/


    /*-------------------------------------------------tool end------------------------------------------------------------*/


    /*-----------------------------------------------------表的处理 关联 删除 汇总------------------------------------------*/
    //改变表名并保存到数据库中
    function changeTableName(json,type) {
        //保存
       /* console.log({
            tableType: json.tableType,
            tbId: json.tbId,
            tableDesc: json.tableName
        });*/
        tools.get({
            url: '/Ibm-Client/updateTable.htm',
            method: 'POST',
            data: {
                tableType: json.tableType,
                tbId: json.tbId,
                tableDesc: json.tableName
            },
            succ: function (resp) {
                if (resp.success) {
                    //通知--slider更新
//                    $rootScope.$broadcast('EditTableName_EV',json.dataType);
                    if(type=="table"){
                        UpdateSliderTable(json.dataType);
                    }else if(type=="mulTable"){
                        var tabletype='';
                        angular.forEach($scope.tablesCard,function(item){
                            if(item.table.tbId==json.tbId){
                               // console.log(item);
                                item.table.tableDesc = json.tableName;
                                tabletype = item.table.tableType;
                            }
                        });
                        //$scope.tablesCard[].table.tableDesc=json.tableDesc;
                        updateMyTable(tabletype);
                    }



                } else {
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                        return;
                    },500);
                   // alert(resp.message);
                }
            }
        });
    }

    //表名的重命名
    $scope.tableNameRename = function (index) {
        var json = {};
        if (index == 1) {
            json = $scope.table1;

        } else if (index == 2) {
            json = $scope.table2;
        }
        $scope.Mulkey = Math.floor(Math.random() * 100000000000);
        //EditorOneInput_EV 组件的调用
        $rootScope.$broadcast('EditorOneInput_EV', {
            title: '重命名',
            data: json.tableName,
            type: 'tableRename',
            id: $scope.Mulkey
        });
        $rootScope.$on('myTable_Rename_EV', function (e, data, id) {
            if (id == $scope.Mulkey) {
                $scope.Mulkey = Math.floor(Math.random() * 100000000000);
                if (index == 1) {
                    $scope.table1.tableName = data;
                    changeTableName($scope.table1,"table");
                } else if (index == 2) {
                    $scope.table2.tableName = data;
                    changeTableName($scope.table2,"table");
                }
            }

        });
    };



    //表关联
    $scope.setConnectLink = function () {
        $timeout(function () {
            $rootScope.$broadcast('MESSAGE_EV', '请再选择一张表')
        }, 100);
        $scope.currTable.connectLinkAble = true;
    };
    //取消关联
    $scope.cancelConLink = function () {
        $rootScope.$broadcast("Saved_it_EV");//去除数据
        // $("#tableLayout").show();
        $scope.currTable.connectLinkAble = false;
        $scope.table2 = null;
        if ($scope.currIbmTable == null) {
            getTable($scope.table1.tbId, $scope.table1.tableType);
        }
    };
    //表关联组件唐初
    $scope.changLinkStuff = function () {

       // console.log($scope.table1);
       // console.log($scope.table2);

        $rootScope.$broadcast('Show_tableConnect_EV', [$scope.table1, $scope.table2]);//表的关联关系组件-tableConnect
    };

    //新建关联表的预览
    $rootScope.$on('IbmRelationTable_EV', function (e, data, joinType) {

        $scope.thMenuShow = true;//Th表头菜单的显示
        $scope.relationDataJson = null;
        $scope.relationDataJson = data;
        //$scope.view = true;
        $('.cur-connect-type').removeClass('toBeConnected').addClass(joinType);

        $scope.fyTable.dataType = "Reltable";
        tools.get({
            url: '/Ibm-Client/getRelationTableDatas.htm',
//            url: '/Ibm-Client/getMultiRelationTableDatas.htm',
            data: data,
            succ: function (resp) {

                $rootScope.$broadcast("loading_End_EV");
                if (resp.success) {

                    $scope.relationAble = true;
                    $scope.currIbmTable = resp.value;
                    //是否为空
                    if ($.isEmptyObject($scope.currIbmTable.datas)) {
                        $scope.currTable.hasNullData = true;
                    }
                    $timeout(function () {
                        myThPosition();
                    }, 10);
                } else {
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                        return;
                    },500);
                    //alert(resp.message);
                }
            }
        });
    });
    //保存关联
    $scope.saveKey = Math.floor(Math.random() * 100000000);
    $scope.saveRelationtable = function () {
        $rootScope.$broadcast('EditorOneInput_EV', {
            title: '创建关联表的表名',
            data: '',
            type: 'ConnectTableName',
            id: $scope.saveKey
        });

        $rootScope.$on('Edit_ConnectTableName_EV', function (e, data, id) {

            if (id == $scope.saveKey) {

                $scope.saveKey = Math.floor(Math.random() * 100000000);

                $scope.relationDataJson.tableName = data;
                tools.get({
                    method: 'POST',
                    url: '/Ibm-Client/addIbmRelationTable.htm',
//                    url: '/Ibm-Client/addMultiRelationTable.htm',
                    data: $scope.relationDataJson,
                    succ: function (resp) {
                        if (resp.success) {
                            getIbmRelationTables($scope.currSource.sourceId);
                            $rootScope.$broadcast('MESSAGE_EV', '保存成功');
                            $rootScope.$broadcast('Saved_it_EV');
                            $scope.relationAble = false;
                            $scope.currIbmTable = null;
                            $scope.table1 = null;
                            $scope.table2 = null;
                            $scope.currTable.connectLinkAble = false;
                        } else {
                            $timeout(function(){
                                $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                                return;
                            },500);
                            //alert(resp.message);
                        }
                    }
                });
            }
        });
    };

    //取消保存关联
    $scope.cancelRelationtable = function () {
        $rootScope.$broadcast('CONFIRM_EV', {
            title: '保存提醒',
            content: '是否保存该关联表',
            btns: {
                no: {
                    text: '取消保存',
                    fn: function () {
                        $rootScope.$broadcast("cancel_save_relationAble_EV");
                    }
                },
                yes: {
                    text: '保存',
                    fn: function () {
                        $rootScope.$broadcast("save_relationAble_EV");
                    }
                }
            }
        });
    };

    //取消表关联保存-$rootScope
    $rootScope.$on('cancel_save_relationAble_EV', function () {
        $scope.relationAble = false;
        $scope.currIbmTable = null;
    });
    //表关联保存
    $rootScope.$on('save_relationAble_EV', function () {
        $scope.saveRelationtable();
    });

    /*--------------------------------------------------------------------------------------*/
    //$scope.AggTableData= null;

//分类汇总
    $scope.tableAggregate = function () {
        event.stopPropagation();
        event.preventDefault();
        /* if($scope.currIbmTable.columns==null){

         }*/

        var data = $scope.currIbmTable.columns;
        $scope.AggTableData = $scope.currIbmTable.columns;
        $rootScope.$broadcast('tableAggregate_EV', $scope.table1, data);
    };
    //分类汇总
    $scope.AggCol = null;
    $scope.tableAgg = function (type, index) {
        $scope.AggCol = null;
        $scope.AggCol = $scope.currIbmTable.columns;
       // console.log($scope.AggCol);



        event.stopPropagation();
        event.preventDefault();

        var data = {};
        data.aggregateTypes = type;
        var col = $scope.currIbmTable.columns[index];

        data.columnDescs = col.columnDesc;
        data.fieldNames = col.fieldName;
        data.columnTypes = col.columnType;
        data.refColumnIds = col.columnId;
        data.refTbId = col.tbId;
        data.refTableType = col.tableType;
        $rootScope.$broadcast("loading_Start_EV");
        $rootScope.$broadcast('addAggregateFunction_EV',data);
        $rootScope.$broadcast("send_ONE_AGG_EV",{"type":type,"columnDesc":col.columnDesc});

       /* tools.get({
            url: '/Ibm-Client/getAggregationTableDatas.htm',
            data: data,
            succ: function (resp) {
                if (resp.success) {

                    $scope.currIbmTable = resp.value;
                    $scope.aggregateAble = true;
                    myThPosition();
                } else {
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","数据异常，请找管理员联系。");
                        return;
                    },500);
                    //alert(resp.message);
                }
            }
        });*/

//        var data= $scope.currIbmTable.columns;
    //    $rootScope.$broadcast('tableAggregate_EV',$scope.table1,data);
    };




    //分类汇总的预览
    $scope.aggregateAble = false;
    $rootScope.$on('addAggregateFunction_EV', function (e, data) {
        $scope.AggregateDataJson = null;
        $scope.AggregateDataJson = data;
        tools.post({
            url: '/Ibm-Client/getAggregationTableDatas.htm',
            data: data,
            succ: function (resp) {

                $rootScope.$broadcast("loading_End_EV");

                if (resp.success) {

                    $scope.currIbmTable = resp.value;

                    $scope.aggregateAble = true;
                    myThPosition();
                    $timeout(function(){
                        $(".ui.dropdown").dropdown();
                        console.log($scope.AggCol);
                    },100);
                } else {
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                        return;
                    },500);
                   // alert(resp.message);
                }
            }
        });
    });
    //保存汇总表
    $scope.saveAggregatetable = function () {
        $scope.aggregateAble = false;
        $rootScope.$broadcast('EditorOneInput_EV', {
            title: '创建汇总表的表名',
            data: '',
            type: 'ConnectTableName',
            id: $scope.saveAggKey
        });
        $rootScope.$on('Edit_ConnectTableName_EV', function (e, data, id) {
           // console.log(data);
          //  console.log($scope.AggregateDataJson);
            if (id == $scope.saveAggKey) {
                $scope.saveAggKey = Math.floor(Math.random() * 1000000000);
                $scope.AggregateDataJson.aggregateTableName = data;
               // console.log($scope.AggregateDataJson);
                tools.get({
                    method: 'POST',
                    url: '/Ibm-Client/addAggregateFunction.htm',
                    data: $scope.AggregateDataJson,
                    succ: function (resp) {
                        if (resp.success) {
                            getIbmAggregateFunctions($scope.currSource.sourceId);
                            $rootScope.$broadcast('MESSAGE_EV', '保存成功');
                            $rootScope.$broadcast("saveAgg_EV");
                            $scope.currIbmTable = null;
                            $scope.table1 = null;

                        } else {
                            $timeout(function(){
                                $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                                return;
                            },500);
//                            alert(resp.message);
                        }
                    }
                });
            }
        });

    };
    $rootScope.$on("Edit_ConnectTableName_C_EV",function(e){
        console.log("CANCEL");
        $scope.aggregateAble = false;
        $scope.currIbmTable = null;
        getTable($scope.table1.tbId, $scope.table1.tableType);
    });
    //取消保存汇总表
    $scope.cancelAggregatetable = function () {
        $rootScope.$broadcast('CONFIRM_EV', {
            title: '保存提醒',
            content: '是否保存该汇总表',
            btns: {
                no: {
                    text: '取消保存',
                    fn: function () {
                        $rootScope.$broadcast("cancel_save_aggregateAble_EV", $scope.table1.tbId, $scope.table1.tableType);
                    }
                },
                yes: {
                    text: '保存',
                    fn: function () {
                        $rootScope.$broadcast("confirm_save_aggregateAble_EV");
                    }
                }
            }
        });
    };
    //取消汇总保存-$rootScope
    $rootScope.$on('cancel_save_aggregateAble_EV', function (e, tbId, tableType) {
        $scope.aggregateAble = false;
        $scope.currIbmTable = null;
        $rootScope.$broadcast("saveAgg_EV");
        getTable(tbId, tableType);
    });
    //汇总保存
    $rootScope.$on('confirm_save_aggregateAble_EV', function () {
        $scope.aggregateAble = false;
        $scope.saveAggregatetable();
    });


    //
    /**
     * 编辑汇总表
     */
    $scope.editTable = function () {
        var dataType = $scope.table1.dataType;
        if (dataType == "Ibm") {
            $scope.addTable();
        } else if (dataType == "Rel") {

        } else if (dataType == "Agg") {
            $rootScope.$broadcast('editTableAggregate_EV', $scope.table1, 1);
        } else if (dataType == "File") {
            $scope.addNewFile();
        }
    };
    //汇总表的更新
    $rootScope.$on('update_TableAggregate', function (e, tbId, tableType) {
        getTable(tbId, tableType);
    });

    /*-------------------------------------------------------表的处理 关联 删除 汇总 end-------------------------------*/


//drag drop
    /*
     数据结构 数组 json
     $scope.tablesCard=[
     {
     table:'',
     field:'',
     linkCol:''
     }
     ];
     * */




    var color = [
        /*"#f00","#e00","#D00","#f06","#f39","#f20","#f36","#F4A",
        "#C63300 ",'#ccc','#f5e8c8', '#b8d2c7', '#c6b38e',*/
        '#a4d8c2', '#f3d999', '#d3758f', '#dcc392', '#2e4783',
        '#82b6e9', '#ff6347', '#a092f1', '#0a915d', '#eaf889',
        '#6699FF', '#ff6666', '#3cb371', '#d5b158', '#38b6b6'];

    $scope.tablesCard = [];//
   // console.log("$scope.tablesCard");
   // console.log($scope.tablesCard);

    function getListFiled(tbId,tableType,arry){
        tools.get({
            method: 'POST',
            url: '/Ibm-Client/getSingleTable.htm',
            data: {
                tbId: tbId,
                tableType:tableType
            },
            succ: function (resp) {
                if (resp.success) {
                    arry.columns = resp.value.columns;
                    angular.forEach(arry.columns,function(item){
                        item.selected = false;
                    });
                }else{
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","数据表获取异常，请找管理员联系。");
                        return;
                    },500);
//                    alert(resp.message);
                }
            }
        });
    }


    //drag slider
    $scope.$on("UI_Cards_EV", function (e, data, x, y,key) {
        if(key==$rootScope.cardKey) {
            if($scope.aggregateAble||$scope.relationAble||$scope.currTable.connectLinkAble|| $scope.table1){
                $scope.currIbmTable = null;
            }       
            $scope.aggregateAble = false;
            $scope.relationAble = false;
            $scope.currTable.connectLinkAble = false;
            $scope.table1 = null;
            $scope.table2 = null;

           // $rootScope.cardKey = Math.floor(Math.random() * 10000000);

            console.log("接受到的数据");
            console.log(data);
          //  console.log("x:" + x + "Y:" + y);


            //init
            if (!$.isEmptyObject($scope.table1)) {
                $scope.table1 = null;
                $scope.currIbmTable = null;
            }




            var json = {};
            json.table = data; //{tbid:"",tabletype:'',tableDesc:""}
            json.id = Math.floor(Math.random() * 1000000000000);
            json.isShow = true;

            json.linkId = [];
            json.linkColIndex = [];
            var length;
        
            $timeout(function () {
            	
                $scope.tablesCard.push(json);

                length= $scope.tablesCard.length;
                console.log("length:"+length);
                var table = $scope.tablesCard[length-1].table;

                //linkCrad_list
                getListFiled(table.tbId, table.tableType ,$scope.tablesCard[length-1]);
            }, 10);
            console.log("$scope.tablesCard:");
            console.log($scope.tablesCard);
            $timeout(function () {


                if (length == 1) {
                    $(".linkAreaCard").eq(0).css({
                        "left": "20px",
                        "top":  "80px"
                    }).show();
                } else {
                    var w = $(".linkAreaCard").width();
                    console.log("w:"+w);
                    $(".linkAreaCard").eq(length - 1).css({
                        "left": (w*(length-1)+20*length) + "px",
                        "top": "80px"
                    }).show();

                   /* $(".linkAreaCard .linkAreaCard_box").eq(length - 1).css({
                        "background":color[(length - 1)%19]
                    });*/
                }
                $(".dropdown").dropdown();
                // alert($(".tableLink")[0].scrollWidth);
                $('i.popup').popup();

               // $(".ui.checkbox.linkHideF").checkbox();

            }, 50);
          //  console.log("    $scope.tablesCard:  ");
           // console.log($scope.tablesCard);
        }

        /* tools.get({
         method: 'POST',
         url: '/Ibm-Client/getTable.htm',
         data: {
         tbId: json.table.tbId,
         tableType:json.table.tabletype
         },
         succ: function (resp) {
         if (resp.success) {
         json.field= resp.value.condition;
         for(var i in json.field){
         json.field[i].isSelected = false;
         }
         $scope.tablesCard.push(json);



         数据结构
         $scope.tablesCard=[
         {
         table:'',
         field:'',
         linkCol:''
         }
         ];

         console.log("$scope.tablesCard");
         console.log($scope.tablesCard);


         $timeout(function(){
         $(".ui.small.card .ui.checkbox").checkbox({
         onChecked:function(){

         },
         onUnchecked:function(){

         }
         });
         console.log(x-230,y-20);
         $("#linkAreaCard").eq($scope.tablesCard.length-1).css({
         "left":x+"px",
         "top":y+"px"
         }).show();


         },100);
         $timeout(function(){
         $(".ui.small.card .ui.checkbox").checkbox({
         onChecked:function(){
         var index = this.getAttribute('fieldIndex');//从1开始的
         // var cardObj=$scope.tablesCard[]
         $timeout(function(){

         $scope.tablesCard[][field][fieldIndex].isSelected=true;
         },100);
         },
         onUnchecked:function(){
         $timeout(function(){
         $scope.tablesCard[][field][fieldIndex].isSelected=true;
         },100);
         }
         });
         },1000);
         }else{
         alert(resp.message);
         }
         }
         });*/
    });
    //table remane
    $scope.LinktableNameRename = function (index) {
       // console.log("index:" + index);
        var json = $scope.tablesCard[index].table;
        $scope.Mulkey = Math.floor(Math.random() * 100000000000);
        //EditorOneInput_EV 组件的调用
        $rootScope.$broadcast('EditorOneInput_EV', {
            title: '重命名',
            data: json.tableDesc,
            type: 'ConnectTableName',
            id: $scope.Mulkey
        });
        $rootScope.$on('Edit_ConnectTableName_EV', function (e, data, id) {
            if (id == $scope.Mulkey) {
                $scope.Mulkey = Math.floor(Math.random() * 100000000000);
                json.tableName = data;
                changeTableName(json,"mulTable");
            }

        });
    };

    $scope.LinkremoveTable = function (index) {
//        alert(index);
        var objs = $(".tableLink svg");
        var bool = false;
        for (var i = 0; i < objs.length; i++) {
            if ($scope.tablesCard[index].id == objs.eq(i).attr("dragId") || $scope.tablesCard[index].id == objs.eq(i).attr("dropId")){
                bool = true;
                break;
            }
        }
       // console.log(bool);
        if (bool) {
            $rootScope.$broadcast('CONFIRM_EV', {
                title: '移除提醒',
                content: '移除将全部清空关联关系',
                btns: {
                    no: {
                        text: '取消',
                        fn: function () {
                            //$rootScope.$broadcast("cancel_save_aggregateAble_EV", $scope.table1.tbId, $scope.table1.tableType);
                        }
                    },
                    yes: {
                        text: '确定',
                        fn: function () {
                            $rootScope.$broadcast("removeLinkTable", $scope.linkTablesShowKey);
                        }
                    }
                }
            });
        } else {
            //console.log("删除tablesCard:" + index);
            $scope.tablesCard.splice(index, 1);
        }
    };





    $scope.linkTablesShowKey=Math.floor(Math.random()*100000000);

    var menus = [
        {
            name: '删除',
            icon: 'remove icon',
            fn: function () {
                $rootScope.$broadcast('CONFIRM_EV',{
                    title: '删除提醒',
                    content: '删除将全部清空关联关系',
                    btns:{
                        no:{
                            text:'取消',
                            fn:function(){
                                //$rootScope.$broadcast("cancel_save_aggregateAble_EV", $scope.table1.tbId, $scope.table1.tableType);
                            }
                        },
                        yes:{
                            text:'确定',
                            fn:function(){
                                $rootScope.$broadcast("removeLinkTable",$scope.linkTablesShowKey);
                            }
                        }
                    }
                });
               // $rootScope.$broadcast("removeLinkTable",$scope.linkTablesShowKey);
            }

        },
        {
            name: '关联',
            icon: 'linkify icon',
            fn: function (){
                    // alert("关联");
                $rootScope.$broadcast("getLinkTable",$scope.linkTablesShowKey);
            }
        }
    ];


    $scope.mulRelationAble = false;
    $scope.cancelMulConLink = function(){
        $scope.mulRelationAble = false;
        $rootScope.$broadcast("removeLinkTable",$scope.linkTablesShowKey);
        $scope.tablesCard = [];
        $scope.panelShow = false;
        $scope.currTable.hasNullData = false;

    };




    //menu 删除
    $rootScope.$on("removeLinkTable",function(e,key){
        if(key==$scope.linkTablesShowKey) {

           // console.log("删除linkTables");


          //  console.log("length:"+$(".tableLink svg").length);

            $scope.mulrelationDataTbId = null;


            $(".tableLink").find("svg").remove();


            $scope.linkPanel = {
                dragTable: {},
                dropTable: {},
                dragField: [],
                dropField: []
            };

            $scope.currIbmTable=null;
            $scope.currTable.hasNullData = false;
            $scope.mulRelationAble = false;
            $scope.linkTablesShowKey=Math.floor(Math.random()*100000000);
        }
    });





    //重新绘制SVG
    function redrawSVG(dragIndex,dropIndex,SvgIndex) {
        var x1,y1,x2,y2;
        x1 = $(".tableLink .linkAreaCard").eq(dragIndex).position().left+$(".tableLink .linkAreaCard").width()/2+$("#rightBox .tableLink").scrollLeft();
        y1 = $(".tableLink .linkAreaCard").eq(dragIndex).offset().top+$("#rightBox .tableLink").scrollTop();
        x2 = $(".tableLink .linkAreaCard").eq(dropIndex).position().left+$(".tableLink .linkAreaCard").width()/2+$("#rightBox .tableLink").scrollLeft();
        y2 = $(".tableLink .linkAreaCard").eq(dropIndex).offset().top+$("#rightBox .tableLink").scrollTop();


       // console.log("x1:"+x1+" y1:"+y1+" x2;"+x2+" y2"+y2);

        var random = Math.floor(Math.random()*20+10);

        var str,width,height,left,top;
        if($("#rightBox .tableLink svg").length==0){
            height = 40;
        }else{
            height = 40+random;
        }
        //height = 20+20;
        if(x1>x2){
            width = x1-x2;
            left = x2;

        }else if(x2>x1){
            width = x2-x1;
            left = x1;
        }

        if(y1>y2){
            height+=(y1-y2);
            top = y1-height+20;
            if(x1>x2){
                str = "0,"+(height-(y1-y2))+" 0,10 "+width+",10 "+width+","+height;
            }else if(x1<x2){
                str = "0,"+height+" 0,10 "+width+",10 "+width+","+(height-(y1-y2));
            }else{

            }

            // str = "0,"+height+" 0,10 "+width+",10 "+width+","+(height-(y1-y2));

        }else if(y2>y1){

            height +=(y2-y1);
            top = (y1+20)-40;

            if(x2>x1){
                str = "0,"+(height-(y2-y1))+" 0,10 "+width+",10 "+width+","+height;
            }else if(x2<x1){
                str = "0,"+height+" 0,10 "+width+",10 "+width+","+(height-(y2-y1));
            }else{}
            //str = "0,40 0,10 "+width+",10 "+width+","+height;
        }else{
            //y2=y1
            top = y1-height+20;
            str = "0,"+height+" 0,"+(10)+" "+width+","+(10)+" "+width+","+height;
        }



        var SVGObj = $(".tableLink svg").eq(SvgIndex)[0];

        SVGObj.style.width=width+"px";
        SVGObj.style.height=height+"px";
        SVGObj.style.left=left+"px";
        SVGObj.style.top=top+"px";

        var rObj = SVGObj.getElementsByTagName("polyline");
        rObj[0].setAttribute("points",str);
        var cObj = SVGObj.getElementsByTagName("rect");

        var cx=(width/2-12);

        cObj[0].setAttribute("x",cx);

        var imObj = SVGObj.getElementsByTagName("image");
        imObj[0].setAttribute("x",cx);
        $("#linkPanel").css({"left":(left+width/2-$("#linkPanel").width()/2)+"px","top":top+18+"px"});

    }

    //draw svg line to line
    function drawLine(dragIndex,dropIndex){
        if($(".tableLink svg").length>0 && $scope.mulrelationDataTbId==null){
            $rootScope.$broadcast("MESSAGE_EV","请先完成第一次关联");
            return;
        }
      //  console.log("    $scope.tablesCard:  ");
       // console.log($scope.tablesCard);
        var x1,y1,x2,y2;
        x1 = $(".tableLink .linkAreaCard").eq(dragIndex).position().left+$(".tableLink .linkAreaCard").width()/2+$("#rightBox .tableLink").scrollLeft();
        y1 = $(".tableLink .linkAreaCard").eq(dragIndex).offset().top+$("#rightBox .tableLink").scrollTop();
        x2 = $(".tableLink .linkAreaCard").eq(dropIndex).position().left+$(".tableLink .linkAreaCard").width()/2+$("#rightBox .tableLink").scrollLeft();
        y2 = $(".tableLink .linkAreaCard").eq(dropIndex).offset().top+$("#rightBox .tableLink").scrollTop();

        var dragId,dropId;
        dragId = $scope.tablesCard[dragIndex].id;
        dropId = $scope.tablesCard[dropIndex].id;

        //init DATA
        $timeout(function(){
        	$scope.linkPanel = null;
	        $scope.linkPanel = {};
	        console.log("45");
	        
        },0);
        
        $timeout(function(){

        	$scope.linkPanel.dragTable = $scope.tablesCard[dragIndex].table;
        	$scope.linkPanel.dropTable = $scope.tablesCard[dropIndex].table;
        	$scope.linkPanel.dragField = $scope.tablesCard[dragIndex].columns;
        	$scope.linkPanel.dropField = $scope.tablesCard[dropIndex].columns;

        },10);


        $scope.dataSum = [0];
        $scope.dataFileds=[{}];

       // getFiled($scope.tablesCard[dragIndex].table.tbId, $scope.tablesCard[dragIndex].table.tableType, 0);//drag
       // getFiled($scope.tablesCard[dropIndex].table.tbId, $scope.tablesCard[dropIndex].table.tableType, 1);//drop

       // console.log("x1:"+x1+" y1:"+y1+" x2;"+x2+" y2"+y2);

        var random = Math.floor(Math.random()*30+10);

        var str,width,height,left,top;
        if($("#rightBox .tableLink svg").length==0){
            height = 40;
        }else{
            height = random+40;
        }
        //height = 20+20;
        if(x1>x2){
            width = x1-x2;
            left = x2;

        }else if(x2>x1){
            width = x2-x1;
            left = x1;
        }

        if(y1>y2){
            height+=(y1-y2);
            top = y1-height+20;
            if(x1>x2){
                str = "0,"+(height-(y1-y2))+" 0,10 "+width+",10 "+width+","+height;
            }else if(x1<x2){
                str = "0,"+height+" 0,10 "+width+",10 "+width+","+(height-(y1-y2));
            }else{

            }
        }else if(y2>y1){

            height +=(y2-y1);
            top = (y1+20)-40;

            if(x2>x1){
                str = "0,"+(height-(y2-y1))+" 0,10 "+width+",10 "+width+","+height;
            }else if(x2<x1){
                str = "0,"+height+" 0,10 "+width+",10 "+width+","+(height-(y2-y1));
            }else{}
        }else{
            //y2=y1
            top = y1-height+20;
            str = "0,"+height+" 0,"+(10)+" "+width+","+(10)+" "+width+","+height;
        }


        var id = dragIndex+'-'+dropIndex;
        var SVGObj='<svg id="'+id+'" dragId="'+dragId+'" dropId="'+dropId+'" xmlns="http://www.w3.org/2000/svg" version="1.1" style="position: absolute;z-index:'+($scope.tablesCard.length)+';left:'+left+'px;top:'+top+'px;width:'+width+'px;height:'+height+'px;">'+
            '<polyline points="'+
            str+
            '" style="fill:none;stroke:#1B6AB9;stroke-width:2" />'+
            '<rect x="'+(width/2-12)+'" y="0" width="24" height="20" fill="#fff"/>'+
            '<image class="cp" xlink:href="/trend-new-BI/assets/img/leftJoinActive.png" x="'+(width/2-12)+'" y="0" height="20" width="24" style="background:#fff"/>'+
            '</svg>';
        SVGObj = $compile(SVGObj)($scope);
        $("#rightBox .tableLink").append(SVGObj);

        //linkPanel
        $timeout(function(){
            $scope.panelShow=true;
            $scope.joinType = 'leftJoin';
        },10);

        $timeout(function(){
            $("#rightBox .tableLink")[0].scrollHeight +=100;
            $("#rightBox .tableLink")[0].scrollTop = $("#rightBox .tableLink")[0].scrollHeight;
        },100);
        $("#linkPanel").css({"left":(left+width/2-$("#linkPanel").width()/2)+"px","top":top+18+"px"});


        $("#linkPanel .actions button").removeAttr("disabled");
        // 右键操作
        $scope.$this;
        $(".tableLink svg#"+id+" image").on('click', function (e) {
           // console.log($(e.target).parent());
            $timeout(function(){
                $scope.$this=$(e.target).parent();
            },0);
            /*if($(e.target).parent().index(".tableLink svg")!=$(".tableLink svg").length-1){
                return;
            }*/
            $rootScope.$broadcast('CONTEXTMENU_EV', e.pageX, e.pageY, menus);

            $rootScope.$on("getLinkTable",function(e,key){
                if(key==$scope.linkTablesShowKey) {


                    $scope.panelShow=true;
                    $scope.joinType=$(".tableLink svg:last image").attr("id");

                    $timeout(function(){
                        $("#rightBox .tableLink")[0].scrollHeight +=80;
                        $("#rightBox .tableLink")[0].scrollTop = $("#rightBox .tableLink")[0].scrollHeight;
                    },10);
                    $scope.linkTablesShowKey=Math.floor(Math.random()*100000000);
                }
            });
            e.preventDefault();
            e.stopPropagation();
            return false;
        });
        
    }


	$scope.panelClick = function(){
		$("#linkPanel").hide();
	};
    //drop has done to link table
   $scope.$on("Drop_Done_EV",function(e,data,key){
        if(key==$rootScope.key) {
//            alert('GGG');
            var dragIndex = data.dragIndex;
            var dropIndex = data.dropIndex;

            if(dragIndex==dropIndex){
                $rootScope.$broadcast("MESSAGE_EV","不能关联自身表，请再选择一张表");
               // console.log("不能关联自己");
                return;
            }


          //  console.log("dragIndex:" + dragIndex + " dropIndex:" + dropIndex);
            var objs = $(".tableLink svg");
            for (var i = 0; i < objs.length; i++) {
               // console.log("drag:" + objs.eq(i).attr("dragId") + "  " + $scope.tablesCard[dragIndex].id);
                if (($scope.tablesCard[dragIndex].id == objs.eq(i).attr("dragId") && $scope.tablesCard[dropIndex].id == objs.eq(i).attr("dropId"))
                    || ($scope.tablesCard[dragIndex].id == objs.eq(i).attr("dropId") && $scope.tablesCard[dropIndex].id == objs.eq(i).attr("dragId"))) {
                    $rootScope.$broadcast("MESSAGE_EV","该关联已存在");
                    return;
                }

            }


            //$scope.mulrelationDataTbId是存在的
           /* if ($scope.mulrelationDataTbId != null) {
                reGetMulTable();
            }*/

            drawLine(data.dragIndex, data.dropIndex);
            $rootScope.key = Math.floor(Math.random()*100000000);
        }
    });



    //重新获取Mul
    /*function reGetMulTable(){
        $scope.pagination = {
            current: 0
        };


        if($.isEmptyObject($scope.linkPanel.dragTable) && $.isEmptyObject($scope.linkPanel.dropTable)){
            console.log("数据清空");
            return;
        }
        var bool = false;
        angular.forEach($scope.currIbmTable.columns,function(item){
            //是否有改变字段
            if(!item.isShow){
                bool = true;
            }
        });
        //bool true 改变过 false 没有改变过
        if(!bool){
            //console.log("没有改变过，不需要重新请求");
            return;
        }

        $(".ui.checkbox.linkHideF input").removeAttr("checked");

      //  console.log(bool);

        var json = {};
        json.relationType = $scope.joinType;
        json.leftTableType = $scope.linkPanel.dragTable.tableType;
        json.rightTableType = $scope.linkPanel.dropTable.tableType;
        json.leftTableId = $scope.linkPanel.dragTable.tbId;
        json.rightTableId = $scope.linkPanel.dropTable.tbId;

        json.leftColumnIds = '';
        json.rightColumnIds = '';

        json.leftColumnFieldNames = '';
        json.rightColumnFieldNames = '';

        json.multiRelationColumnIds = '';
        json.multiRelationColumnFields = '';
        json.multiLeftColumnsDesc = '';
        json.multiRightColumnsDesc = '';
        json.multiLeftColumnsType = '';
        json.multiRightColumnsType = '';

        //关联的columniIds
        angular.forEach($scope.dataFileds, function (item) {
            json.multiRelationColumnIds += item.leftData.columnId + '=' + item.rightData.columnId + ',';
            json.multiRelationColumnFields += item.leftData.fieldName + '=' + item.rightData.fieldName + ',';
        });
        angular.forEach($scope.currIbmTable.columns,function(item){
            if(item.isShow){
                angular.forEach($scope.linkPanel.dragField, function (itemleft) {//table1
                    if (item.refColumnId == itemleft.columnId && item.refTbId == itemleft.tbId) {

                        json.leftColumnIds += itemleft.columnId+",";
                        json.leftColumnFieldNames += itemleft.fieldName+",";

                        json.multiLeftColumnsType += itemleft.columnType + ',';
                        json.multiLeftColumnsDesc += itemleft.columnDesc + ',';
                    }
                });
                angular.forEach($scope.linkPanel.dropField, function (itemright) {//table2
                    if (item.refColumnId == itemright.columnId && item.refTbId == itemright.tbId) {

                        json.rightColumnIds += itemright.columnId+",";
                        json.rightColumnFieldNames += itemright.fieldName+",";

                        json.multiRightColumnsType += itemright.columnType + ',';
                        json.multiRightColumnsDesc += itemright.columnDesc + ',';
                    }
                });
            }
        });

        $scope.currIbmTable = null;

        tools.post({
            url: '/Ibm-Client/getMultiRelationTableDatas.htm',
            data: json,
            succ: function (resp) {
                $rootScope.$broadcast("loading_End_EV");
                if (resp.success) {

                    $scope.mulRelationAble = true;

                    $scope.currIbmTable = resp.value;
                    //是否为空
                    if($.isEmptyObject($scope.currIbmTable.datas)){
                        $scope.currTable.hasNullData=true;
                    }
                    $scope.mulrelationDataTbId=resp.value.tbId;
                    myThPosition();


                    console.log($scope.tablesCard);
                    $timeout(function(){
                        angular.forEach($scope.tablesCard,function(item,index){
                           angular.forEach($scope.currIbmTable.columns,function(item2,index2){
                               if(item.table.tbId==item2.refTbId){
                                   $("#tableLayout .myTh").eq(index2).css({"background":color[index%19]});
                               }
                           });
                        });
                    },100);


                    *//* $scope.fyTable.tbId = resp.value.tbId;
                     $scope.fyTable.tableType ="multi_relation";*//*


                }else{
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","表关联异常，请找管理员联系。");
                        return;
                    },500);
//                    alert(resp.message);
                }
            }
        });
    }*/



    /**
     * 获取字段
     * @param tbId
     * @param tableType
     * @param index  第几个表 表1 or 表2
     */
    function getFiled(tbId, tableType, index) {
        tools.get({
            method: 'POST',
            url: '/Ibm-Client/getSingleTable.htm',
            data: {
                tbId: tbId,
                tableType:tableType
            },
            succ: function (resp) {
                if (resp.success) {
                    $scope.currTable.hasNullData = false;
                    if(index == 0){
                        $scope.linkPanel.dragField = resp.value.columns;
                    }else{
                        $scope.linkPanel.dropField = resp.value.columns;
                    }

                }else{
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                        return;
                    },500);
//                    alert(resp.message);
                }
            }
        });
    }

//linkPanel 关联
    $scope.linkPanel={
        dragTable:{},
        dropTable:{},
        dragField:[],
        dropField:[]
    };
    //下拉框的个数--字段的关联--init
    $scope.dataSum = [0];
    //存储选择的字段关联的信息---init
    $scope.dataFileds = [{}];
    //增加字段
    $scope.addSum = function () {

        $scope.dataFileds.push({});
        $scope.dataSum.push($scope.dataSum.length);
       // console.log($scope.dataFileds);
    };

    //删除字段
    $scope.lessSum = function (index) {
        if($scope.dataSum.length==1){
            return;
        }
        $scope.dataSum.splice(index, 1);
        $scope.dataFileds.splice(index, 1);
    };


    $scope.joinType = 'leftJoin';

    $scope.mulrelationDataTbId = null;

    //确定多表关联--预览
    $scope.okMulRel = function(){
        $scope.pagination = {
            current: 0
        };
        if ($scope.joinType == null) {
            $scope.msg = '请选择表的关联类型';
            $timeout(function(){
                $scope.msg = null;
            },2000);
            return;
        }
        //关联的字段没有选择
        var selectBoolean = true;
        angular.forEach($scope.dataFileds, function (item) {
            if (item.left == null || item.right == null) {
                $scope.msg = '请选择下拉框';
                selectBoolean = false;
                return;
            }
        });
        if (!selectBoolean) {
            $timeout(function(){
                $scope.msg = null;
            },2000);
            return;
        }
        if($("svg").length==1&&$scope.mulrelationDataTbId){
            $scope.mulrelationDataTbId = null;
        }
        if($("svg").length>1){
            $("#linkPanel .actions button").attr({"disabled":"disabled"});
        }


        //关闭并loading
        $rootScope.$broadcast("loading_Start_EV");
        $scope.panelShow=false;
       // console.log($scope.dataFileds);//{left:colId,right:colId}

         //所有的字段选择信息----scope.dataFileds--从table中获取相应的值

        angular.forEach($scope.dataFileds, function (item) {//数组json
            angular.forEach($scope.linkPanel.dragField, function (itemleft) {//table1
                if (item.left == itemleft.columnId) {
                    item.leftData = {};
                    item.leftData.columnType = itemleft.columnType;
                    item.leftData.columnId = itemleft.columnId;
                    item.leftData.fieldName = itemleft.fieldName;
                    item.leftData.columnDesc = itemleft.columnDesc;
                    return;
                }
            });
            angular.forEach($scope.linkPanel.dropField, function (itemright) {//table2
                if (item.right == itemright.columnId) {
                    item.rightData = {};
                    item.rightData.columnType = itemright.columnType;
                    item.rightData.columnId = itemright.columnId;
                    item.rightData.fieldName = itemright.fieldName;
                    item.rightData.columnDesc = itemright.columnDesc;
                    return;
                }
            });
        });
       // console.log($scope.dataFileds);
       // return;
       // console.log("linkPanel");
       // console.log($scope.linkPanel);

        var json = {};

        json.relationType = $scope.joinType;
        json.leftTableType = $scope.linkPanel.dragTable.tableType;
        json.rightTableType = $scope.linkPanel.dropTable.tableType;
        json.leftTableId = $scope.linkPanel.dragTable.tbId;
        json.rightTableId = $scope.linkPanel.dropTable.tbId;

        json.leftColumnIds = '';
        json.rightColumnIds = '';

        json.leftColumnFieldNames = '';
        json.rightColumnFieldNames = '';

        json.multiRelationColumnIds = '';
        json.multiRelationColumnFields = '';
        json.multiLeftColumnsDesc = '';
        json.multiRightColumnsDesc = '';
        json.multiLeftColumnsType = '';
        json.multiRightColumnsType = '';

        //select
        angular.forEach($scope.linkPanel.dragField, function (item) {
            if(item.selected) {
                json.leftColumnFieldNames += item.fieldName + ',';
                json.leftColumnIds += item.columnId + ',';
                json.multiLeftColumnsType += item.columnType + ',';
                json.multiLeftColumnsDesc += item.columnDesc + ',';
            }
        });
        //alert(json.leftColumnFieldNames === "");

        //not
        if(json.leftColumnFieldNames===""){

            angular.forEach($scope.linkPanel.dragField, function (item) {
                if(item.isShow) {
                    json.leftColumnFieldNames += item.fieldName + ',';
                    json.leftColumnIds += item.columnId + ',';
                    json.multiLeftColumnsType += item.columnType + ',';
                    json.multiLeftColumnsDesc += item.columnDesc + ',';
                }
            });
        }
        //select
        angular.forEach($scope.linkPanel.dropField, function (item) {
            if(item.selected) {
                json.rightColumnFieldNames += item.fieldName + ',';
                json.rightColumnIds += item.columnId + ',';
                json.multiRightColumnsType += item.columnType + ',';
                json.multiRightColumnsDesc += item.columnDesc + ',';
            }
        });
        //not
        if(json.rightColumnFieldNames === ""){
            angular.forEach($scope.linkPanel.dropField, function (item) {
                if(item.isShow) {
                    json.rightColumnFieldNames += item.fieldName + ',';
                    json.rightColumnIds += item.columnId + ',';
                    json.multiRightColumnsType += item.columnType + ',';
                    json.multiRightColumnsDesc += item.columnDesc + ',';
                }
            });
        }

        //关联的columniIds
        angular.forEach($scope.dataFileds, function (item) {
            json.multiRelationColumnIds += item.leftData.columnId + '=' + item.rightData.columnId + ',';
            json.multiRelationColumnFields += item.leftData.fieldName + '=' + item.rightData.fieldName + ',';
        });

        if($scope.mulrelationDataTbId!=null){
            json.tbId = $scope.mulrelationDataTbId;
        }

        $scope.fyTable={};
        $scope.currIbmTable = null;
        //return;
        tools.post({
            url: '/Ibm-Client/getMultiRelationTableDatas.htm',
            data: json,
            succ: function (resp) {
                $rootScope.$broadcast("loading_End_EV");
                if (resp.success) {
                    $scope.mulRelationAble = true;

                    $scope.currIbmTable = resp.value;
                    //是否为空
                    if($.isEmptyObject($scope.currIbmTable.datas)){
                        $scope.currTable.hasNullData=true;
                    }
                    $scope.mulrelationDataTbId=resp.value.tbId;


                    $rootScope.$broadcast("loading_End_EV");


                    var imgUrl;
                    if($scope.joinType=='leftJoin'){
                        imgUrl= '/trend-new-BI/assets/img/leftJoinActive.png';
                    }else if($scope.joinType=='innerJoin'){
                        imgUrl = '/trend-new-BI/assets/img/innerJoinActive.png';
                    }else if($scope.joinType=='rightJoin'){
                        imgUrl= '/trend-new-BI/assets/img/rightJoinActive.png';
                    }else if($scope.joinType=='outerJoin'){
                        imgUrl= '/trend-new-BI/assets/img/outJoinActive.png';
                    }else{
                        imgUrl= '/trend-new-BI/assets/img/leftJoinActive.png';
                    }
                    $(".tableLink svg:last image").attr("xlink:href",imgUrl);
                    $(".tableLink svg:last image").attr("id",$scope.joinType);

                    //init
                    $scope.joinType = 'leftJoin';
                    $timeout(function(){
                        $('label.popup').popup();
                        myThPosition();
                        console.log($scope.tablesCard);
                       /* $timeout(function(){
                            angular.forEach($scope.tablesCard,function(item,index){
                                angular.forEach($scope.currIbmTable.columns,function(item2,index2){
                                    if(item.table.tbId==item2.refTbId){
                                        $("#tableLayout .myTh").eq(index2).css({"background":color[(index%19)]});
                                    }
                                });
                            });
                        },100);*/
                    },10);

                }else{
                    //init
                    $scope.joinType = 'leftJoin';
                    $timeout(function(){
                        $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                        return;
                    },500);
//                    alert(resp.message);
                }
            }
        });

    };

    //勾选要展示的字段
    $(".ui.checkbox.linkHideF").checkbox({
        onChecked: function () {
            $timeout(function(){
               console.log("hideAll");
                $scope.currTable.isShowAll=true;

                angular.forEach($scope.currIbmTable.columns,function(item){
                    item.isShow = false;
                });
            },0);
        },
        onUnchecked: function () {
            $timeout(function(){
               console.log("showAll");
                $scope.currTable.isShowAll= false;

                angular.forEach($scope.currIbmTable.columns,function(item){
                    item.isShow = true;
                });
            },0);

        }
    });


    $scope.changeW = function(){
        console.log("th 调整宽度");
        myThPosition();
    };
    //给th调整宽度
    function myThPosition(){
        //console.log("th 调整宽度");
        $timeout(function(){
            console.log($("#tableLayout thead tr").width()<$("#tableLayout").width());
            var tdsObj = $("#tableLayout tbody tr:first td");
            var thsObj = $("#tableLayout thead tr th");
            if($("#tableLayout thead tr").width()<$("#tableLayout").width()){

                for(var i = 0;i<thsObj.length;i++){
                    //console.log(tdsObj.eq(i).width());
                    if(tdsObj.eq(i).width()==null){
                       // console.log("td is not has data");
                        thsObj.eq(i).css({"width":($("#tableLayout").width()/thsObj.length)+"px"});
                    }else{
                        thsObj.eq(i).css({"width":tdsObj.eq(i).outerWidth()+"px"});
                    }

                }
            }else{
                for(var i = 0;i<thsObj.length;i++){
                    //console.log(tdsObj.eq(i).width());
                    if(tdsObj.eq(i).width()==null){
                        // console.log("td is not has data");
                        thsObj.eq(i).css({"width":($("#tableLayout").width()/thsObj.length)+"px"});
                    }else{
                        thsObj.eq(i).css({"width":tdsObj.eq(i).outerWidth()+"px"});
                    }

                }
            }
        },10);
    }

    $scope.getLinkField = myThPosition;






    //svgmove-divmove
    function svgMoveDivMove(){
        console.log("SVGMOVE");


       // console.log("cardMoveIndex   "+cardMoveIndex);
//        var cardIndex = cardMoveIndex;
        var id = $scope.tablesCard[cardMoveIndex].id;


       // console.log("id:  "+id);


//        var dragIndex,dropIndex;
//        var objs = $(".tableLink svg");
        var objs = angular.element(".tableLink svg");
       // console.log("objs:  "+objs.length);
       // console.log(objs);
       // console.log($scope.tablesCard);
        angular.forEach(objs,function(item,d){
        //    console.log(d);
         //   console.log("jq");

            if(id==$(item).attr("dropId")){
                angular.forEach($scope.tablesCard,function(item2,index){
                    if(item2.id==$(item).attr("dragId")){
                      //  console.log(index+" "+cardMoveIndex+" "+d);
                        redrawSVG(index,cardMoveIndex,d);
                    }
                });
            }
            else if(id==$(item).attr("dragId")){
                angular.forEach($scope.tablesCard,function(item3,index){
                    if(item3.id==$(item).attr("dropId")){
                      //  console.log(index+" "+cardMoveIndex+" "+d);
                        redrawSVG(cardMoveIndex,index,d);
                    }
                });
            }
        });
        /*for(var i=0;i<objs.length;i++){
            console.log(i);
            console.log(objs.eq(i).attr("dropId"));
            if(id==objs.eq(i).attr("dropId")){
                angular.forEach($scope.tablesCard,function(item,index){
                    if(item.id==objs.eq(i).attr("dragId")){
                        console.log(index+" "+cardMoveIndex+" "+i);
                        redrawSVG(index,cardMoveIndex,i);
                    }
                });
            }
            else if(id==objs.eq(i).attr("dragId")){
                angular.forEach($scope.tablesCard,function(item,index){
                    if(item.id==objs.eq(i).attr("dropId")){
                        console.log(index+" "+cardMoveIndex+" "+i);
                        redrawSVG(cardMoveIndex,index,i);
                    }
                });
            }
        }*/

        //redrawSVG(dragIndex,dropIndex);
    }

    //tableCard的移动
    var cardMoveIndex,objX,objY;
    $scope.linkCardMove = function(event,index){

        cardMoveIndex=index;

//
//        console.log("top:"+$(".linkArea.card").eq(index).offset().top+" left:"+$(".linkArea.card").eq(index).offset().left);
//        console.log("pageY:"+event.pageY+" pageX:"+event.pageX);


        objX=event.pageX-$(".linkAreaCard").eq(index).offset().left;
        objY=event.pageY-$(".linkAreaCard").eq(index).offset().top;//y??

        $(document).mousedown(function(){
            $(document).on("mousemove",docuMove);
        });
//        $(".linkAreaCard").on("mousemove",svgMoveDivMove);
        $(document).on("mouseup",removeDocuMove);

    };

    function docuMove(event){

        var index=cardMoveIndex;
        var left=event.pageX+$("#rightBox .tableLink").scrollLeft()-objX;
        var top=event.pageY+$("#rightBox .tableLink").scrollTop()-objY;
        var pf=$("#rightBox").css("paddingLeft");//230px;
        console.log("left:"+left+" top:"+top);

        /*if($(".linkArea.card").eq(index).offset().top>200){
            $("#rightBox .tableLink").scrollTop(200);
        }*/

      /* if(event.pageX>($(window).width()-200)){
            console.log("scroolLeft");
            $("#rightBox .tableLink").scrollLeft(200);

        }if(event.pageY>($("#rightBox .tableLink").height()*0.6)){
            console.log("scroolTop");
            $("#rightBox .tableLink").scrollTop(300);

        }*/
//        console.log("start move"+index);

        if(left<235||top<5){
            $(document).mouseup(function(){removeDocuMove()});
            return;
        }

        $(".linkAreaCard").eq(index).css({
            "left":left-pf.substr(0,pf.length-2)+"px",
            "top":top+"px",
            "zIndex":109
        });
        svgMoveDivMove();
        if(!$.isEmptyObject($scope.tablesCard[index].linkId)){
            angular.forEach($scope.tablesCard[index].linkId,function(item){
//                var id = item;
               // console.log("id:"+item);
                redrawSVG(item);
            });
        }

        $(document).on("mouseup",removeDocuMove);
    }

    function removeDocuMove(){

        var index=cardMoveIndex;
       // console.log("end move index");

        $(".linkAreaCard").eq(index).css({
            "zIndex":104
        });
        $(document).off("mousemove");
        $(document).off("mousedown");
        $(document).off("mouseup");

    }



    //保存多表关联
    $scope.saveKey = Math.floor(Math.random()*100000000);
    $scope.saveMulRelationtable = function(){
       // reGetMulTable();
        $rootScope.$broadcast('EditorOneInput_EV', {
            title: '创建关联表的表名',
            data: '',
            type: 'MulRelTableName',
            id:$scope.saveKey
        });



        $rootScope.$on('Edit_ConnectTableName_EV2', function (e, data,id) {
            var tableName = data;
            if(id == $scope.saveKey){

                $scope.saveKey = Math.floor(Math.random()*100000000);

                var tableName = data;
                tools.get({
                    url: '/Ibm-Client/saveMultiRelationTable.htm',
                    data: {
                        tableDesc:tableName,
                        tbId:$scope.mulrelationDataTbId
                    },
                    succ: function (resp) {
                        if (resp.success) {
                            UpdateSliderTable("mulRel");
                            $rootScope.$broadcast('MESSAGE_EV', '保存成功');
                            //$rootScope.$broadcast('Saved_Mulit_EV');

                            $scope.mulRelationAble = false;
                            $scope.currIbmTable = null;

                            $scope.currTable.mulConnectLinkAble = false;

                            $scope.tablesCard=[];
                            $rootScope.$broadcast("removeLinkTable", $scope.linkTablesShowKey);

                        }else{
                            $timeout(function(){
                                $rootScope.$broadcast("MESSAGE_EV","表关联异常，请找管理员联系。");
                                return;
                            },500);
//                            alert(resp.message);
                        }
                    }
                });
            }
        });
    };

    //取消保存*多表关联
    $scope.cancelMulRelationtable = function(){
        $rootScope.$broadcast('CONFIRM_EV',{
            title: '取消提醒',
            content: '是否取消保存该关联表',
            btns:{
                no:{
                    text:'取消',
                    fn:function(){
                        //$rootScope.$broadcast("cancel_save_mulRelationAble_EV");
                    }
                },
                yes:{
                    text:'确认',
                    fn:function(){
                        //$rootScope.$broadcast("confirm_save_mulRelationAble_EV");
                        $rootScope.$broadcast("cancel_save_mulRelationAble_EV");
                    }
                }
            }
        });
    };


    //取消*多表关联保存-$rootScope
    $rootScope.$on('cancel_save_mulRelationAble_EV',function(){
        $scope.mulRelationAble = false;
        $scope.currIbmTable = null;
        $scope.mulrelationDataTbId = null;
        $scope.currTable.hasNullData = false;
    });
    //*多表关联保存
    $rootScope.$on('confirm_save_mulRelationAble_EV',function(){
        $scope.saveRelationtable();
    });



    /*模块--字段清晰*/



    $scope.maxSize = true;
    $scope.sizeChangeDiv = function(el,size){
        if(size == "max"){
            $(el).height(600);
            $scope.maxSize = false;
        }
        else if(size == "min"){
            $scope.maxSize = true;
            $(el).height($(el).attr("size"));
        }
    }

}]);